<?php
declare(strict_types=1);
/**
 * Created by project.
 * User: huanzipap
 * Date: 2023/5/10
 * Time: 11:25
 */

namespace App\Controller\Admin;

use App\Controller\AppBaseController;
use App\Model\Task;
use App\Model\Notify;


use App\Model\User;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\AdminApiAuth;

#[Controller(prefix: 'admin')]
#[Middleware(AdminApiAuth::class)]
class TaskController extends AppBaseController
{
    /**
     * 后台--支部任务列表
     * @return object
     */
    #[RequestMapping(path:'taskList',methods: 'get')]
    public function taskList(): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where = [];
            //指定支部
            if($_admin->level==1){
                $party_id = $this->request->input('party_id', null);
                if($party_id){
                    $where['party_id'] = $party_id;
                }
            }else{
                $where['party_id'] = $_admin->party_id;
            }

            $list = Task::where($where)
                ->selectRaw('id,type,title,party_list,created_at')
                ->orderByDesc('id')
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Task::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支部任务详情
     * @param int $task__id
     * @return object
     */
    #[RequestMapping(path:'taskInfo/{task__id}',methods: 'get')]
    public function workInfo(int $task__id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $info = Task::where('id',$task__id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            return $this->reMsg->re(1,'success',$info);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支部任务发布|编辑
     * @param int|null $task_id
     * @return object
     */
    #[RequestMapping(path: 'taskEdit[/{task_id}]',methods: 'post,get')]
    public function taskEdit(int|null $task_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            $data = $this->request->all();

            //虚拟数据
//            if(empty($data)){
//                $data['title'] = 'hdrm';
//                $data['content'] = 'fghrthrstsjrtssrtj';
//                $data['media_list'] = [
//                    '0'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                    '1'=>'fqxinyi23/test/xyWords/xyWords1691110928830.jpg',
//                ];
//                $data['type'] = 2;
//                $data['party_list'] = [1,2,3];
//                $data['status'] = 1;
//            }
            //虚拟数据

            if( empty(($data['type']) || !in_array($data['type'],[1,2]))
                || empty($data['title'])
                || empty($data['media_list']) || !is_array($data['media_list'])
            ){
                return $this->reMsg->re(10007);
            }
            empty($data['status']) || !is_numeric($data['status']) ? $data['status'] = 0 : $data['status'] = 1;

            //只超级管理员操作
            if($_admin->level==1){
                $party_id = $_admin->party_id;
//              if(!isset($data['party_id']) || $data['party_id']==null) return $this->reMsg->re(10007);
//              $party_id = $data['party_id'];
            }else{
                $party_id = $_admin->party_id;
            }

            if($task_id){
                //编辑
                $info = Task::where('id',$task_id)->first();
                if(empty($info)) return $this->reMsg->re(10008);

                //验证权限（仅限超级管理员）
                if($_admin->level!=1) return $this->reMsg->re(10009);

                $info->type = $data['type'];
                $info->title = $data['title'];
                $info->content = $data['content'];
                $info->media_list = $data['media_list'];
//                $info->party_list = $data['party_list'];
                $info->status = $data['status'];
                $info->party_id = $party_id;
                $info->admin_id = $_admin->id;
                $info->save();
                return $this->reMsg->re(1);
            }else{
                $data['party_id'] = $party_id;
                $data['admin_id'] = $_admin->id;
                $insertRet = Task::create($data);
                if($insertRet){
                    //向选择的党支部 管理员和支部管理员 推送
                    //先查询所有党支部的 管理员和支部管理员
//                    $userList = User::whereIn('user_type',[8,9])->whereIn('party_id',$data['party_list'])->selectRaw('id,party_id')->get();

                    //推送所有党支部 党员、党支部书记、党委委员
                    $userList = User::whereIn('user_type',[2,8,10])->selectRaw('id,party_id')->get();
                    if($userList->isNotEmpty()){
                        foreach ($userList as $key=>$value) {
                            $notifyData['party_id'] = $value->party_id;
                            $notifyData['module'] = 2;
                            $notifyData['relation_id'] = $insertRet->id;
                            $notifyData['uid'] = $value->id;
                            Notify::create($notifyData);
                        }
                    }
                    return $this->reMsg->re(1);
                }else{
                    return $this->reMsg->re(0);
                }
            }
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }


    /**
     * 后台--支部任务|删除
     * @param int $task_id
     * @return object
     */
    #[RequestMapping(path:'taskDelete/{task_id}',methods: 'get')]
    public function taskDelete(int $task_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);
            $_admin = $checkInfo['data'];

            //判断信息
            $info = Task::where('id',$task_id)->first();
            if(empty($info)) return $this->reMsg->re(10008);
            //验证权限（仅限超级管理员）
            if($_admin->level!=1) return $this->reMsg->re(10009);
            $info->delete();
            //同时删除自己的关联通知
            $notifyWhere['module'] = 2;//支部任务
            $notifyWhere['relation_id'] = $info->id;
            Notify::where($notifyWhere)->delete();

            return $this->reMsg->re(1);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }



    /**
     * 后台--支部任务完成列表
     * @param int $task_id
     * @return object
     */
    #[RequestMapping(path:'taskJoinList/{task_id}',methods: 'get')]
    public function taskJoinList(int $task_id): object
    {
        try{
            //验证管理员信息
            $checkInfo = $this->checkAdmin();
            if($checkInfo['status']==40002) return $this->reMsg->re(10002,$checkInfo['message']);

            $page = $this->request->input('page', 1);
            $limit = $this->request->input('limit', 20);
            $offset = ($page - 1) * $limit;

            $where['task_id'] = $task_id;
            $list = Notify::with(['user'=>function($query){
                    $query->selectRaw('id,nickname,avatar,auth_name')->get();
                }])
                ->selectRaw('id,uid,created_at')
                ->where($where)
                ->offset($offset)
                ->limit($limit)
                ->get();

            $total = 0;
            $next = 0;
            if($list->isNotEmpty()){
                if($page==1) $total = Notify::where($where)->count();
                if(count($list)>$limit) $next = 1;
            }
            return $this->reMsg->re(1,'success',['list' => $list,'next' => $next,'total'=>$total]);
        }catch (\Exception $exception){
            return $this->diyError->errorJson($exception);
        }
    }





}